$(function() {
//Declare variable
var 	tips = $( ".validateTips" ),
		button_name="",
		url="a_receive.php", 
		branchID="",
		ID="",
		mode="",
		rowSelect="";
		
		ID=$("#val").val();
		mode=$("#mode").val();
		//Load First page

		LoadData(1,false,ID);
	
		//Show Loading bar			
		function showLoader(){
			$( "#resultData tbody:first" ).prepend( "<tr>"
						+"<td colspan=9 class='search-background'>"
						+"<label><img src='./images/ajax-loader.gif'/></label>"
						+"</td>"
						+"</tr>" ); 
			 $('.search-background').fadeIn(900,0);
		}
		//Hide Loading bar			
		function hideLoader(){
			$('.search-background').fadeOut(300);
			$( "#resultData tbody tr" ).remove();
		};
		
		//Dialog
		$( "#dialog-modal" ).dialog({
			modal: true,
			height: 120,
			zIndex:9999,
			resizable: false,
			autoOpen: false
		});

		$( "#dialog:ui-dialog" ).dialog( "destroy" );
	
		
		//b=false , don't gennerate paging
		function LoadData(page,b,id){
			$( "#resultData tbody tr" ).remove();
			//Show loading
			showLoader();
			//set criteria
			 //Post 			
			var data={};
			data={'m':'view','id':id,'page':page,'type':mode};
						
			$.post(url,data,function(data){
				//hide loading
				//alert(data);
				hideLoader();
				var obj=eval("(" + data + ")");
				var ar=eval("("+obj['header']+")");
			
				$("#totalAmt").attr('innerHTML', CommaFormatted(parseFloat(ar['Total']).toFixed(2)));
				$("#iCode").attr('innerHTML',(ar['Code']));
				$("#iName").attr('innerHTML',(ar['SupplierName']));
				$("#iCreateDate").attr('innerHTML',(ar['CreatedDate']));
				$("#iTerm").attr('innerHTML',(ar['CreditTerm']));
				$("#iStatus").attr('innerHTML',(ar['Status']));
				if (mode=="d"){
					$("#iReDate").attr('innerHTML',(ar['ReceivedDate']));		
					$("#iReBy").attr('innerHTML',(ar['ReceivedBy']));								
				}
				
				$( "#resultData tbody tr" ).remove();
				
				$( "#resultData tbody" ).append(obj['data']);
				
				//set row 
				$("#rowCount").attr('innerHTML',obj['rows']);
				
				if (mode=='d'){
					//set page
					if (b ){
						var p="<ul>";
						for (var i=parseInt(obj['totalpage']);i >0 ;i--){
							p = p +'<li id="'+i+'">'+i+'</li>';
						}
						p = p+"</ul>";
						$("#paging_button ul").remove();
						$("#paging_button").append(p);
						 
					}
					$("#"+page).css({'background-color' : '#006699'});
				}
			
			});
			
		}
	$(".amt_rc").live('keypress',function(e){
		if( e.which!=8 && e.which!=0 && (e.which<48 || e.which>57)){
			return false;
		}
	});		
	
	$(".amt_rc").live('keyup',function(e){
			var iPrice = new Number($(this).parent().parent().find("td").eq(9).html().replace(',','').replace(',',''));
			var iVal = new Number($(this).val());
			var iTotal = iPrice * iVal;
			var rTotal=0;
			$(this).parent().parent().find("td").eq(10).html(CommaFormatted(iTotal.toFixed(2))).css({color:'red'});
			
			$('#resultData tbody tr').each(function() {
				var i= new Number( $(this).find("td").eq(10).html().replace(',','').replace(',','') );
				rTotal += i; 
			});
			
			$("#totalAmt").attr('innerHTML', CommaFormatted(rTotal.toFixed(2)));
	});	
	
	$("#btnCheck").live('click' ,function(){
		var arlist=[];
		
		// Get value from table
		$('#resultData tbody tr').each(function() {
			// receive id detail
			var reid = $(this).find("td").eq(1).html();    
			// Product ID 
			var pdid = $(this).find("td").eq(2).html();    
			// Product ID 
			var cost = $(this).find("td").eq(9).html().replace(',','').replace(',',''); 
			// receive amount
			var amt = $(this).find("input[name=amt_rc]").val().replace(',','').replace(',','');     
			
			if (isNaN(amt) || amt==''){
				amt=0
			}
			arlist.push({'id': reid , 'pdid': pdid ,'amt':amt,'cost':cost});
			 
		 });
		 
		var Total= $("#totalAmt").attr('innerHTML').replace(',','').replace(',','');
		 
		// alert(ID);
		$.ajax({
				type: 'POST',
				cache: false,
				url: url,
				data: {"m":"add_rc","var":arlist,"id":ID,"total":Total },
				success: function(data){
					//alert(data);
					$("#dialog-modal").dialog("open");
					$("#dialog-modal").dialog("option","buttons",	{
						"OK": function() {
							$( this ).dialog( "close" );
							history.back(-1);
						}
					});
					
					
				}
			});
		return false; 
	});
	$("#btnBack").live('click',function(){
		//alert('d');
		history.back(-1);
	});
	
	$("#paging_button li").live('click',function(){
		$("#paging_button li").css({'background-color' : ''});
 		LoadData(this.id,false,ID);

	});
	
	function CommaFormatted(amount)
	{
	 
		var delimiter = ","; // replace comma if desired
		var a = amount.split('.',2)
		var d = a[1];
		var i = parseInt(a[0]);
		if(isNaN(i)) { return ''; }
		var minus = '';
		if(i < 0) { minus = '-'; }
		i = Math.abs(i);
		var n = new String(i);
		var a = [];
		while(n.length > 3)
		{
			var nn = n.substr(n.length-3);
			a.unshift(nn);
			n = n.substr(0,n.length-3);
		}
		if(n.length > 0) { a.unshift(n); }
		n = a.join(delimiter);
		if(d.length < 1) { amount = n; }
		else { amount = n + '.' + d; }
		amount = minus + amount;
		return amount;
	}
});
	